<template>
  <div class="activity-management">
    <h2 class="title">运动管理</h2>
    <div class="toolbar">
      <el-input
          v-model="searchQuery"
          placeholder="搜索活动"
          style="width: 200px; margin-right: 10px;"
          @input="fetchActivities"
      />
      <el-button type="primary" @click="openAddDialog">添加活动</el-button>
    </div>
    <el-dialog :visible.sync="dialogVisible" title="添加/编辑活动" width="40%" @close="handleDialogClose">
      <el-form :model="newActivity" :rules="rules" ref="activityForm" class="activity-form" label-width="120px">
        <el-form-item label="活动类型" prop="activityType">
          <el-select v-model="newActivity.activityType" placeholder="请选择活动类型">
            <el-option label="跳绳" value="跳绳"></el-option>
            <el-option label="游泳" value="游泳"></el-option>
            <el-option label="跑步" value="跑步"></el-option>
            <el-option label="散步" value="散步"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="持续时间" prop="duration">
          <el-input v-model="newActivity.duration" type="number" placeholder="请输入持续时间（分钟）"></el-input>
        </el-form-item>
        <el-form-item label="地点" prop="location">
          <el-input v-model="newActivity.location"></el-input>
        </el-form-item>
        <el-form-item label="强度" prop="intensity">
          <el-input v-model="newActivity.intensity"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
              v-model="newActivity.startTime"
              type="datetime"
              placeholder="选择开始时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
              v-model="newActivity.endTime"
              type="datetime"
              placeholder="选择结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="validateForm">{{ isEditing ? '更新' : '添加' }}</el-button>
          <el-button @click="resetForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <div class="table-container">
      <el-table :data="activities" style="width: 100%" class="activity-table">
        <el-table-column prop="activityType" label="活动类型"></el-table-column>
        <el-table-column prop="duration" label="持续时间"></el-table-column>
        <el-table-column prop="location" label="地点"></el-table-column>
        <el-table-column prop="intensity" label="强度"></el-table-column>
        <el-table-column prop="startTime" label="开始时间" :formatter="formatDate"></el-table-column>
        <el-table-column prop="endTime" label="结束时间" :formatter="formatDate"></el-table-column>
        <el-table-column label="星期几">
          <template slot-scope="scope">
            {{ getWeekday(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="editActivity(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="confirmDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page.sync="page"
            @current-change="fetchActivities"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { Message, MessageBox } from 'element-ui';

export default {
  name: 'ActivityManagement',
  data() {
    return {
      activities: [],
      searchQuery: '',
      newActivity: {
        id: '',
        activityType: '',
        duration: '',
        location: '',
        intensity: '',
        startTime: '',
        endTime: '',
        createdAt: '',
        updatedAt: ''
      },
      headers: {
        token: localStorage.getItem('token'),
      },
      isEditing: false,
      total: 0,
      page: 1,
      pageSize: 10,
      dialogVisible: false,
      rules: {
        activityType: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
        duration: [{ required: true, message: '请输入持续时间', trigger: 'blur' }],
        location: [{ required: true, message: '请输入地点', trigger: 'blur' }],
        intensity: [{ required: true, message: '请输入强度', trigger: 'blur' }],
        startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
      },
    };
  },
  created() {
    this.fetchActivities();
  },
  methods: {
    fetchActivities() {
      axios.get('/activity/list', {
        params: {
          pageNum: this.page,
          pageSize: this.pageSize,
          activityType: this.searchQuery
        }
      })
          .then(response => {
            this.activities = response.data.data.rows;
            this.total = response.data.data.records;
          })
          .catch(error => {
            console.error('Error fetching activities:', error);
          });
    },
    addActivity() {
      axios.post('/activity/add', this.newActivity)
          .then(() => {
            this.fetchActivities();
            this.resetForm();
            Message.success('添加成功');
          })
          .catch(error => {
            console.error('Error adding activity:', error);
          });
    },
    editActivity(activity) {
      this.newActivity = { ...activity };
      this.isEditing = true;
      this.dialogVisible = true;
    },
    updateActivity() {
      axios.put('/activity/update', this.newActivity)
          .then(() => {
            this.fetchActivities();
            this.resetForm();
            Message.success('更新成功');
          })
          .catch(error => {
            console.error('Error updating activity:', error);
          });
    },
    confirmDelete(id) {
      MessageBox.confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteActivity(id);
      }).catch(() => {
        Message.info('已取消删除');
      });
    },
    deleteActivity(id) {
      axios.delete(`/activity/delete/${id}`)
          .then(() => {
            this.fetchActivities();
            Message.success('删除成功');
          })
          .catch(error => {
            console.error('Error deleting activity:', error);
          });
    },
    resetForm() {
      this.newActivity = {
        id: '',
        activityType: '',
        duration: '',
        location: '',
        intensity: '',
        startTime: '',
        endTime: '',
        createdAt: '',
        updatedAt: ''
      };
      this.isEditing = false;
      this.dialogVisible = false;
    },
    handleDialogClose() {
      this.resetForm();
    },
    openAddDialog() {
      this.resetForm();
      this.isEditing = false;
      this.dialogVisible = true;
    },
    validateForm() {
      this.$refs.activityForm.validate((valid) => {
        if (valid) {
          this.isEditing ? this.updateActivity() : this.addActivity();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    formatDate(row, column, value) {
      if (!value) return '';
      const date = new Date(value);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    },
    getWeekday(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      const weekdays = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
      return weekdays[date.getDay()];
    },
  }
};
</script>

<style scoped>
.activity-management {
  height: 100vh;
  overflow: hidden;
  background-image: url('../assets/pdx.png');
  background-size: cover;
  background-position: center;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  padding: 20px;
  box-sizing: border-box;
}

.title {
  color: black;
  margin-top: 20px;
}

.toolbar {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  margin-bottom: 20px;
}

.activity-form {
  width: 100%;
  margin-bottom: 20px;
}

.table-container {
  width: 100%;
}

.pagination-container {
  margin-top: 20px;
}

.activity-table {
  background-color: white;
}
</style>
